<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/30
 * Time: 13:49
 */

namespace Lm\Controllers;

use \Admin\Frontend\Controllers\ControllerBase;
use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\overt\XhovertAreainfo;
use Helpers\Assets;
use Helpers\Hrm;
use Helpers\Main;
use Helpers\Template;
use Helpers\Tool;
use Helpers\User;
use Helpers\UserPower;
use Helpers\XhException;
use Admin\Models\lm\XHLmRenter;
use Admin\Models\lm\XHLmRentHouse;
use Admin\Models\lm\XHLmRentPay;

class RentController extends ControllerBase
{
//    public function indexAction(){
//        return $this->sendViewError('错误');
//    }

    public $enums = [
        'payType' => [
            1 => '年付',
            2 => '月付',
            3 => '季付',
            4 => '半年付',
        ],
        'bRent' => [
            1 => '在租',
            0 => '退租'
        ]
    ];


    /**
     * 检查类型
     * @param $type
     * @param string $operater
     * @return bool
     * create by dale 20180327
     */
    public function checkPower($type,$operater=''){
        if($type == 1){
            $tag = 'Lm_RentHouse';
        }else if($type == 2){
            $tag = 'Lm_RentHouse_Renter';
        }else if($type == 3){
            $tag = 'Lm_RentHouse_Pay';
        }else{
            return false;//不存在标签类型
        }
        if($operater != ''){
            $tag .= '_'.ucfirst($operater); //首字母大写
        }
        return UserPower::checkUserPower($tag);
    }

    /**
     * 错误信息
     * @param bool $isView
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     * create by dale 20180327
     */
    public function sendPowerMsg($isView=false){
        if($isView){
            return $this->sendViewError('没有权限');
        }else{
            return $this->sendErrorResponse(400,'缺少权限');
        }
    }


    /**
     * 房间列表
     *
     * create by dale 20180402
     */
    public function houseListAction()
    {
        if (!$this->checkPower(1)) {
            return $this->sendPowerMsg(true);
        }
        Assets::easyUI();
        Assets::importJs('js/rent/houseList.js');
        Assets::sweetAlert2();
        $this->view->pick('rent/houseList');
        Template::exists('houseList', 'list') or die(Main::showMessageModal('houseList 配置文件不存在，请先创建！', 109106002));
        $listButton = $listSearchArr = [];
        if ($this->checkPower(1, 'add')) {
            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
        }
        if ($this->checkPower(1, 'edit')) {
            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_unRent', 'text' => '退租', 'icon' => 'fa-pencil');
        }
        if ($this->checkPower(1, 'del')) {
            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }

        $secArea = Hrm::getDepArray('XHYYB', 1 , true);
        $secArea = array_column($secArea  ,  'text' , 'id');
        $rent = [
            ''  => '全部 ',
            '2' => '在租',
            '1' => '退租'
        ];
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_rent', 'data' => $rent, 'default' => '2');
        $secArea[''] = '请选择运营区';
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_secArea', 'data' => $secArea, 'default' => '');
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_thirdArea', 'data' => ['' => '请选择运营县' ], 'default' => '');
        $enums['province'] = array_column(array_values($this->getAreaByLevel(1)),'areaName','areaCode');
        $enums['province'][''] = '--请选择省--';
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_province', 'data' => $enums['province'], 'default' => '');
        $enums['city'][''] = '--请选择市--';
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_city', 'data' => $enums['city'], 'default' => '');
        $enums['county'][''] = '--请选择县--';
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_county', 'data' => $enums['county'], 'default' => '');
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');

        $this->view->setVars(array(
            'List' => Template::createList('list', 'houseList', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButton),

            ]),
            'Form' => true,
        ));
    }

    /**
     * 退租
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181017
     */
    public function unRentAction()
    {
        try {
            $ids = $this->request->getPost('ids', 'string');
            $desc = $this->request->getPost('desc', 'string');
            if (!$ids) {
                return $this->sendErrorResponse(500, '缺少参数');
            }
            if (!is_array($ids)) {
                $ids = explode(',', $ids);
            }
            $objArr = XHLmRentHouse::find([
                'conditions' => 'bDelete = 0 and iRHId in ({ids:array}) ',
                'bind'       => ['ids' => $ids]
            ]);
            $this->db->begin();
            foreach ($objArr as $obj) {
                $obj->bRent = 0;
                $obj->mUnRentDesc = $desc;
                if (!$obj->save()) {
                    throw new XhException('退租保存失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('退租成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 根据父id获取子部门
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by xjq 20180514
     */
    public function findAreaAction($id)
    {
        $tag = $this->request->getPost('tag', 'string');
        if ($tag) {
            return $this->sendJsonResponse(XhhrmDepart::getDeps($id));
        }
        $thirdDeps = XhhrmDepart::getDeps($id);
        $arr = [];
        $arr[] = [ 'id' => '' , 'text' => '请选择运营县'];
        foreach ($thirdDeps as $index => $row) {
            $arr [] = [ 'id' => $index , 'text' => $row];
        }
        return $this->sendJsonResponse($arr);
    }

    /**
     * 获取数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by dale 20180402
     */
    public function getHouseAction(){
        if (!$this->checkPower(1)){
            return $this->sendPowerMsg();
        }
        $key      = $this->request->getPost('key' , 'string');
        $province = $this->request->getPost('province','string');
        $city     = $this->request->getPost('city','string');
        $county   = $this->request->getPost('county','string');
        $secArea  = $this->request->getPost('secArea','string');
        $thirdArea = $this->request->getPost('thirdArea','string');
        $bRent     = $this->request->getPost('rent','string');
        try{
            $builder = $this->modelsManager->createBuilder()
                ->from('Admin\\Models\\lm\\XHLmRentHouse')
                ->columns('*')
                ->where('bDelete = 0 ');
            if($key){
                $builder->andWhere('sLandlord like :key: or sAddress like :key: or sLandPhone like :key: ' , ['key' => '%'.$key.'%']);
            }
            if ($bRent) {
                $bRent = $bRent -1 ;
                $builder->andWhere('bRent = :bRent:', ['bRent' => $bRent]);
            }
            if ($province && $province != '--请选择省--') {
                $builder->andWhere('sProvince =:province:' ,  array('province' => $province));
            }

            if ($city && $city != '--请选择市--') {
                $builder->andWhere('sCity =:city:' ,  array('city' => $city));
            }

            if ($county && $county != '--请选择县--') {
                $builder->andWhere('sCounty =:county:' ,  array('county' => $county));
            }

            if($secArea){
                $builder->andWhere('iSecArea =:secArea:' ,  array('secArea' => $secArea));
            }

            if($thirdArea){
                $builder->andWhere('iThirdArea =:thirdArea:' ,  array('thirdArea' => $thirdArea));
            }

            $data = Main::runBuilderPage($builder, ['bRent' =>$this->enums['bRent']]);
            $ids = array_column($data['rows'] , 'iRHId');
            if(count($ids) > 0){
                $houseInfo = $this->modelsManager->createBuilder() //人员信息
                ->columns("r.iRHId,r.iStaffId,s.sStaffName,r.bDelete,r.tOutDate,r.bCharge,s.sSelfPhone")
                    ->from(['r'=>'Admin\\Models\\lm\\XHLmRenter'])
                    ->leftJoin("Admin\\Models\\hrm\\XhhrmStaff" , "s.iStaffId = r.iStaffId" , 's')
                    ->where('r.tOutDate is null and r.iRHId  in ({ids:array}) and r.bDelete = 0' , ['ids' => $ids] )
                    ->getQuery()->execute()->toArray();
            }
            $nameById = [];
            foreach ($houseInfo as $row){
                $str = '';
                if($row['bCharge'] == 1 ){
                    $str = ' color="#0066cc" ';
                }
                $nameById[$row['iRHId']][] = '<font '.$str.' title="'.$row['sSelfPhone'].'" >'.$row['sStaffName'].'</font>';

            }
            Main::runUserNameById($data['rows'] ,['iCreateUserId' => 'iCreateUserId'] ,true );
            $deps = XhhrmDepart::getDepEnum();
            Tool::runEnum($data['rows'] , [
                'iSecArea' => $deps,
                'iThirdArea' => $deps
            ]);
            foreach ($data['rows'] as $index => &$row){
                if(isset($nameById[$row['iRHId']])){
                    $row['renters'] = implode(' , ' ,  $nameById[$row['iRHId']] );
                }
            }
            unset($row);
            return $this->sendJsonResponse($data);
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }

    /**
     * 新增表单
     *
     * create by dale 20180402
     */
    public function addFormAction(){
        if (!$this->checkPower(1,'add')){
            return $this->sendPowerMsg(true);
        }
        $this->view->pick('rent/addForm');
        Assets::select2();
        $staff['市场部'] = Hrm::getDepStaffByTag('XHSCB');
        $staff['运营部'] = Hrm::getDepStaffByTag('XHYYB');

        $this->view->setVars([
            'province' => json_encode($this->getAreaByLevel(1)),
            'city'     => json_encode($this->getAreaByLevel(2)),
            'county'   => json_encode($this->getAreaByLevel(3)),
            'staff'    => $staff,
//            'payType'  => ,
        ]);
    }

    /**
     * 保存信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180402
     */
    public function saveInfoAction(){
        $data = $this->request->getPost();
        try{
            if (!isset($data['iRHId']) ) {
                if (!$this->checkPower(1,'add')){
                    return $this->sendPowerMsg();
                }
                $obj = new XHLmRentHouse();
            }else{
                if (!$this->checkPower(1,'edit')){
                    return $this->sendPowerMsg();
                }
                $obj = XHLmRentHouse::findFirst($data['iRHId']);
            }
            $obj->assign($data);

            if(!$obj->save()){
                return $this->sendErrorResponse(500,'保存失败');
            }

            return $this->sendSuccessResponse('保存成功');
        }catch (\Exception $e){
            return $this->sendErrorResponse(400,$e->getMessage());
        }

    }

    /**
     * 删除
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     * create by xjq 20180514
     */
    public function delHouseAction(){
        $id = $this->request->getPost('id');
        if (!$this->checkPower(1)){
            return $this->sendPowerMsg(false);
        }
        $house = XHLmRentHouse::findFirst($id);
        if (!User::isAdmin() && $house->iCreateUserId != Main::getLoginUserInfo('userId') ) {
            return $this->sendErrorResponse(401 , '没有权限');
        }
        $house->bDelete = 1;
        if (!$house->save() ) {
            return $this->sendErrorResponse( 500 , '删除失败');
        }
        return $this->sendSuccessResponse('删除成功');
    }

    /**
     * houseTab
     *
     * create by dale 20180402
     */
    public function houseTabAction($iRHId){
        if (!$this->checkPower(1)){
            return $this->sendPowerMsg(true);
        }
        $this->view->pick('rent/houseTab');
        Assets::select2();
        Assets::importJs('js/rent/houseTab.js');
        $staff['市场部'] = Hrm::getDepStaffByTag('XHSCB');
        $staff['运营部'] = Hrm::getDepStaffByTag('XHYYB');
        $info = XHLmRentHouse::findFirst($iRHId);
        if (!$info) {
            return $this->sendViewError('未找到数据');
        }
        $pay = XHLmRentPay::findFirst([
            'columns'    => 'tEndDate',
            'conditions' => 'bDelete = 0 and iRHId = :iRHId:',
            'bind'       => ['iRHId' => $info->iRHId],
            'order'   => 'tEndDate desc',
        ]);
        if ($pay) {
            $this->view->setVar('str','截止入住时间：'.$pay->tEndDate);
        }
        $this->view->setVars([
            'province' => json_encode($this->getAreaByLevel(1)),
            'city'     => json_encode($this->getAreaByLevel(2)),
            'county'   => json_encode($this->getAreaByLevel(3)),
            'info'     => json_encode($info->toArray()),
            'staff'    => $staff,
            'iRHId'    => $iRHId,
            'power'    => $this->checkPower(1,'edit'),
            'secArea'  => array_column(Hrm::getDepArray('XHYYB',1,true) , 'text' ,'id'),
        ]);
    }


    /**
     * 获取地区等级
     *
     * @param $level
     * @return array
     *
     * create by dale 20180402
     */
    public function getAreaByLevel($level){
        $area = XhovertAreainfo::find([
            'conditions' => ' areaLevel = :level:',
            'bind'       => ['level'=> $level ]
        ])->toArray();
        $area = array_column($area,null,'areaCode');
        return $area;
    }

    /**
     * 人员列表
     *
     * create by dale 20180403
     */
    public function renterListAction(){
        if (!$this->checkPower(2)){
            return $this->sendPowerMsg(true);
        }
        Assets::easyUI();
        Assets::importJs('js/rent/renterList.js');
        Assets::sweetAlert2();
        $this->view->pick('rent/renterList');
        Template::exists('renterList', 'list') or die(Main::showMessageModal('renterList 配置文件不存在，请先创建！', 109106002));
        $listButton = [];
        if ($this->checkPower(2,'add')) {
            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
        }
        if ($this->checkPower(2,'del')) {
            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        if ($this->checkPower(2,'edit')){
            $listButton[] = array('plain' => 'true', 'id' => 'bt_setDefault', 'text' => '设置负责人', 'icon' => 'fa-pencil');
        }

        $this->view->setVars(array(
            'List' => Template::createList('list', 'renterList', [
//                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButton),

            ]),
        ));
    }

    /**
     * 获取租客列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180403
     */
    public function getRenterAction($iRHId){
        if (!$this->checkPower(2)){
            return $this->sendPowerMsg();
        }
        $builder = $this->modelsManager->createBuilder()
            ->from(['r'=>'Admin\\Models\\lm\\XHLmRenter'])
            ->columns('r.iRSId,r.iRHId,r.iStaffId,r.bCharge,r.tInDate,r.tOutDate,s.sStaffName,s.sSelfPhone')
            ->leftJoin('Admin\\Models\\hrm\\XhhrmStaff','r.iStaffId = s.iStaffId','s')
            ->where('r.bDelete = 0 and  r.iRHId = :iRHId: ',['iRHId' => $iRHId]);

        $data = Main::runBuilderPage($builder);
        foreach ($data['rows'] as $index=>$row){
            $color = '#2baab1';
            if($row['bCharge'] == 1){
                $color = '#0066cc';
            }
            if ($row['tOutDate'] != null) {
                $color = '#CCCCCC';
            }
            $data['rows'][$index]['info'] = '<i class="fa fa-user" style="color:'.$color.'" ></i>';
        }
        return $this->sendJsonResponse($data);

    }


    /**
     * 租客表单
     *
     * @param $iRHId
     * @param $iRSId
     * 
     * create by dale 20180403
     */
    public function renterFormAction($iRHId=null,$iRSId=null){
        $this->view->pick('rent/renterForm');
        Assets::select2();
        Assets::datetimePicker();
        Assets::importJs('js/rent/renterForm.js');
        $staffs = XhhrmStaff::find([
            'columns'    => 'iStaffId,sStaffName',
            'conditions' => 'bDelete = 0'
        ])->toArray();
        $staffs = array_column($staffs,'sStaffName','iStaffId');

        $webArr = [
            'staffs' => $staffs,
            'iRHId'  => $iRHId,
        ];
        if($iRSId){
            $info = XHLmRenter::findFirst($iRSId)->toArray();
            $webArr['info'] = json_encode($info);
            if (!$this->checkPower(2,'edit')) {
                $webArr['check'] = '<script>parent.$(\'#bt_modal_confirm\').hide();</script>';
            }
        }
        $this->view->setVars($webArr);
    }

    /**
     * 保存租客
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180404
     */
    public function saveRenterAction(){
        $data = $this->request->getPost();
        if(isset($data['iRSId'])&& $data['iRSId']){
            if (!$this->checkPower(2,'edit')) {
                return $this->sendPowerMsg();
            }
            $obj = XHLmRenter::findFirst($data['iRSId']);
        }else{
            if (!$this->checkPower(2,'add')) {
                return $this->sendPowerMsg();
            }
            $obj = new XHLmRenter();
        }
        $data = array_filter($data);
        $obj->assign($data);
        if (!$obj->save() ) {
            return $this->sendErrorResponse(500, '保存失败');
        }

        return $this->sendSuccessResponse('保存成功');
    }

    /**
     * 删除接口
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180404
     */
    public function delRenterAction(){
        if (!$this->checkPower(2,'del')) {
            return $this->sendPowerMsg();
        }
        $ids = $this->request->getPost('ids');
        if(!is_array($ids)){
            $ids = explode(',',$ids);
        }
        try{
            $renters = XHLmRenter::find([
                'conditions' => 'bDelete = 0 AND iRSId in ({ids:array}) ',
                'bind'       => ['ids'=> $ids]
            ]);
            $this->db->begin();
            foreach ($renters as $renter){
                $renter->bDelete = 1;
                if(!$renter->save()){
                    $this->db->rollback();
                    return $this->sendErrorResponse(500,'删除失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('删除成功');
        }catch (\Exception $e){
            $this->db->rollback();
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }

    /**
     * 设置负责人
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180404
     */
    public function setChargeAction(){
        if (!$this->checkPower(2,'edit')) {
            return $this->sendPowerMsg();
        }
        $iRSId = $this->request->getPost('iRSId','int');
        $iRHId = $this->request->getPost('iRHId','int');
        try{
            $renter = XHLmRenter::findFirst([
                'conditions' => 'bDelete = 0  AND iRSId = :iRSId:',
                'bind'        => ['iRSId' => $iRSId]
            ]);
            if($renter->bCharge == 1){
                return $this->sendErrorResponse(400,'已经是负责人不需要重复设置');
            }
            $renters =  XHLmRenter::find([
                'conditions' => 'bDelete =0  AND iRHId = :iRHId: ',
                'bind'       => ['iRHId' => $iRHId],
            ]);
            $this->db->begin();
            foreach ($renters as $obj){
                $obj->bCharge = 0;
                if(!$obj->save()){
                    $this->db->rollback();
                    return $this->sendErrorResponse(500,'设置失败');
                }
            }
            $renter->bCharge = 1;
            if(!$renter->save()){
                $this->db->rollback();
                return $this->sendErrorResponse(500,'设置失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');
        }catch (\Exception $e){
            $this->db->rollback();
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }

    /**
     * 支付列表
     *
     * create by dale 20180409
     */
    public function payListAction(){
        if (!$this->checkPower(3)) {
            return $this->sendPowerMsg(true);
        }
        Assets::easyUI('', true);
        Assets::importJs('js/rent/payList.js');
        Assets::sweetAlert2();
        $this->view->pick('rent/payList');
        Template::exists('payList', 'list') or die(Main::showMessageModal('payList 配置文件不存在，请先创建！', 109106002));
        $listButton = [];
        if ($this->checkPower(3,'add')){
            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
        }
        if ($this->checkPower(3,'reimburse')){  //报销确认
            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_reimburse', 'text' => '报销确认', 'icon' => 'fa fa-paypal');
        }
        if ($this->checkPower(3,'del')){
            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        $this->view->setVars(array(
            'List' => Template::createList('list', 'payList', [
//                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButton),
            ])
        ));
    }

    /**
     * @param $iRHId
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180409
     */
    public function getPayAction($iRHId){
        if (!$this->checkPower(3)){
            return $this->sendPowerMsg();
        }
        try{
            $builder = $this->modelsManager->createBuilder()
                ->columns('p.*')
                ->from(['p'=>'Admin\\Models\\lm\\XHLmRentPay'])
                ->where('p.bDelete = 0 and p.iRHId = :iRHId:',['iRHId'=>$iRHId]);

            $data = Main::runBuilderPage($builder,['iState'=>[1=>'已支付',0=>'未支付']]);
            foreach ($data['rows'] as &$row) {
                if ($row['bReimburse'] == 1) {
                    $row['mReimburse'] = unserialize($row['mReimburse']);
                }
            }
            return $this->sendJsonResponse($data);
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }

    /**
     * 支付表单
     *
     * create by dale 20180409
     */
    public function payFormAction($iRHId='',$iRPId=''){
        $this->view->pick('rent/payForm');
        Assets::datetimePicker();
        Assets::importJs('js/rent/payForm.js');
        $webArr = [
            'iRHId' => $iRHId
        ];
        if($iRPId){
            $info = XHLmRentPay::findFirst($iRPId);
            if($info){
                $webArr['info'] = json_encode($info->toArray());
            }
            if (!$this->checkPower(3,'edit')){
                $webArr['check'] = '<script>parent.$(\'#bt_modal_confirm\').hide();</script>';
            }
        }
        $this->view->setVars($webArr);
    }

    /**
     * 保存支付信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180409
     */
    public function savePayAction(){
        $data = $this->request->getPost();
        try{
            if(isset($data['iRPId']) && $data['iRPId'] ){
                if (!$this->checkPower(3,'edit')){
                    return $this->sendPowerMsg();
                }
                $obj = XHLmRentPay::findFirst($data['iRPId']);
            }else{
                if (!$this->checkPower(3,'add')){
                    return $this->sendPowerMsg();
                }
                $obj = new XHLmRentPay();
            }
            $obj->assign($data);
            if(!$obj->save()){
                return $this->sendErrorResponse(500,'保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }

    /**
     * 删除pay
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180409
     */
    public function delPayAction(){
        if (!$this->checkPower(3,'del')){
            return $this->sendPowerMsg();
        }
        $ids = $this->request->getPost('ids');
        if(!is_array($ids)){
            $ids = explode(',',$ids);
        }
        try{
            $this->db->begin();
            foreach ($ids as $id){
                $obj = XHLmRentPay::findFirst($id);
                $obj->bDelete = 1;
                if(!$obj->save()){
                    return $this->sendErrorResponse(500,'保存失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }

    /**
     * 报销确认
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180817
     */
    public function reimburseAction(){
        $this->view->pick('rent/reimburse');
        $this->di->get('assets')
            ->addCss('assets/fileinput/fileinput.css')
            ->addJs('../customer/js/fileinput.min.js')//修改过的
            ->addJs('../customer/js/zh.js');
        Assets::importJs('../customer/js/myMain.js');
        Assets::importJs('js/rent/reimburse.js');
        return $this->view->setVars([

        ]);
    }

    /**
     * 保存报销确认
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180817
     */
    public function saveReimburseAction(){
        try {
            $id = $this->request->getPost('id', 'int');
            $postData = $this->request->getPost();
            if (!$id) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $obj = XHLmRentPay::findFirst($id);
            if (!$obj) {
                return $this->sendErrorResponse(400, '没有找到该支付记录');
            }
            $obj->bReimburse = 1;
            $obj->mReimburse = [
                'file' => $postData['list'],
                'content' => $postData['mContent']
            ];;
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e instanceof XhException ? $e->getDescription() : $e->getTrace());
        }
    }

    /**
     * 文件上传
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     *
     * create by dale  20180817
     */
    public function ajaxUploadAction(){
        $this->view->disable();
        if(!$this->request->hasFiles()){
          return $this->sendErrorResponse(400, '没有文件上传');
        }
        $file = $this->request->getUploadedFiles()[0];
        $name = $file->getName();
        if (!$name) {
            return $this->sendErrorResponse(400, '没有文件上传');
        }
        $fullPath = TEMP_PATH . $name;
        if (!is_writable(TEMP_PATH)) {
            $this->db->rollback();
            return $this->sendErrorResponse(500 , TEMP_PATH . '缓存无写入权限');
        }
        $file->moveTo($fullPath);
        $url = Main::uploadToFileManageSystem($fullPath, 'other', null, true);
        @unlink($fullPath);
        return json_encode(array('url' => $url, 'fileName' => $name));
    }


}